﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Diagnostics;

namespace DoubleH.Utility.IO
{
    public class StartThreads : IDisposable
    {
        /// <summary>
        /// 传入的Socket实例
        /// </summary>
        private Socket socket;
        /// <summary>
        /// 定义私有的线程
        /// </summary>
        private Thread thread;
        /// <summary>
        /// 是否坚挺中
        /// </summary>
        private bool isListenner;
        /// <summary>
        /// 保存文件的位置
        /// </summary>
        private string saveFilePath;
                
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="socket">Socket实例</param>
        /// <param name="objForm">窗体实例</param>
        /// <param name="filePath">文件保存位置</param>
        /// <param name="SaveAS">按发送时间另存设置</param>
        /// <param name="DelTime">删除多少天之前的文件</param>
        public StartThreads(Socket socket)
        {
            this.socket = socket;
            isListenner = true;

            thread = new Thread(new ThreadStart(WriteFile));
            thread.Start();

        }

        private void WriteFile()
        {
            string FileLastName;
            //获取线程ID
            string ThID = Thread.CurrentThread.ManagedThreadId.ToString();
            IPEndPoint clientep = (IPEndPoint)socket.RemoteEndPoint;
            //开始接受数据
            //接受文件名
            string fileName = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(socket));
            //接受文件大小
            string fileSize = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(socket));
            //接受包的大小
            string filebagSize = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(socket));
            //接受包的数量
            string filebagCount = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(socket));
            //接受最后一个包的大小
            string fileLastbagSize = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(socket));
            //接受文件MD5值
            //string fileMD5 = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(socket));

            if (fileName != "" && fileSize != "")
            {
                //获取文件后缀名
                FileLastName = fileName.Substring(fileName.LastIndexOf("."));

                string SaveFile = saveFilePath + "\\" + fileName.Substring(0, fileName.LastIndexOf(".")) + ".SDM";
                    //当文件以覆盖形式保存时，直接使用原始文件名及后缀
                    SaveFile = saveFilePath + "\\" + fileName.Substring(0, fileName.LastIndexOf(".")) + FileLastName;

                System.IO.FileStream _myFileStream = new System.IO.FileStream(SaveFile, System.IO.FileMode.Create, System.IO.FileAccess.Write);

                int SendBagCount = 0;
                while (true)
                {
                    byte[] data = TransferFiles.ReceiveVarData(socket);
                    if (data.Length == 0)
                        break;
                    else
                    {
                        SendBagCount++;
                        _myFileStream.Write(data, 0, data.Length);
                    }
                    //if (Convert.ToInt64(_myFileStream.Length) == Convert.ToInt64(fileSize))
                    //{
                    //    ////接受文件MD5值
                    //    //OldFileMD5 = System.Text.Encoding.Unicode.GetString(TransferFiles.ReceiveVarData(socket));

                    //    //_objForm.SetListBoxMsg = "线程[" + ThID + "]原始文件MD5值：【" + OldFileMD5 + "】";
                    //}
                }

                _myFileStream.Dispose();
                _myFileStream.Close();
            }

            socket.Close();
        }

        public void Dispose()
        {
            isListenner = false;
            //确定线程状态是否为空，并结束该线程
            if (thread != null)
            {
                if (thread.ThreadState != System.Threading.ThreadState.Aborted)
                    thread.Abort();

                thread = null;
            }

            //判断连接是否已经断开。并结断开该连接
            if (socket != null)
            {
                socket.Shutdown(SocketShutdown.Both);
                socket.Close();
            }
        }
    }
}
